/*
    MUDServ - A Multi-User Dungeon Server
    Client Library Functions for C#
    
    Copyright (c) 2009, Ecl3ctic Software
    All rights reserved.
    
    Redistribution and use in source and binary forms, with or without
    modification, are permitted provided that the following conditions are met:
    
    * Redistributions of source code must retain the above copyright notice,
    this list of conditions and the following disclaimer.
    * Redistributions in binary form must reproduce the above copyright notice,
    this list of conditions and the following disclaimer in the documentation
    and/or other materials provided with the distribution.
    * Neither the name of Ecl3ctic Software nor the names of its contributors
    may be used to endorse or promote products derived from this software
    without specific prior written permission.
    
    THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
    AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
    IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
    ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
    LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
    CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
    SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
    INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
    CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
    ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
    POSSIBILITY OF SUCH DAMAGE.
*/

using System;
using System.Text;
using System.Net.Sockets;

public class ClientLib {
	private Socket sock;
    private Byte[] buffer = new Byte[50];
    private static ASCIIEncoding encoding = new ASCIIEncoding();
    private static String[] noResponseCommands = { "quit" };
    
	public ClientLib(String host, Int32 port) {
        sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
        sock.Connect(host, port);
	}

    // Waits for a response from the server (usually called by ExecuteCommand)
    //
    // Return value: an array with the format [code, data] where code is an integer
    //              response code and data is any string data returned by the server
    public String[] GetResponse() {
        String[] response = { "-1", "0" };
        Boolean startedMessage = false, completedMessage = false;
        Boolean dataStarted = false;
        String code = "", data = "";
        
        try {
            do {
                // Read a character from the socket
                sock.Receive(buffer, 1, SocketFlags.None);

                // Check if we have a '/' character. If so we have received either
                // the start or end sentinel
                if ((char)buffer[0] == '/') {
                    if (!startedMessage) {
                        startedMessage = true;
                    }
                    else {
                        completedMessage = true;
                    }
                }
                else if ((char)buffer[0] == ' ' && !dataStarted) {
                    dataStarted = true;
                }
                else if (dataStarted) {
                    data += (char)buffer[0];
                }
                else {
                    code += (char)buffer[0];
                };
            } while(!completedMessage);
        }
        catch {
            return response;
        }

        response[0] = code;
        response[1] = data;
        return response;
    }

    // Executes a command on the server with no arguments
    //
    // Return value: an array with the format [code, data] where code is a
    //              response code and data is any string data returned by the server
    public String[] ExecuteCommand(String cmd) {
        String[] args = { };
        return ExecuteCommand(cmd, args);
    }

    // Executes a command on the server with arguments given in args
    //
    // Return value: an array with the format [code, data] where code is a
    //              response code and data is any string data returned by the server
    public String[] ExecuteCommand(String cmd, String[] args) {
        String[] response = { "0", "0" };
        Boolean getResponse = true;
        
        // Start off the string with the sentinel character and the command
        String cmdString = "/" + cmd.ToLower();
        
        // Add the arguments
        foreach (String arg in args) {
            cmdString += " " + arg;
        }

        // Finish off the command string
        cmdString += "/";

        // Send it away!
        sock.Send(encoding.GetBytes(cmdString));

        // Check if we are NOT supposed to get a response
        foreach (String noResCmd in noResponseCommands) {
            if (noResCmd == cmd.ToLower()) {
                getResponse = false;
            }
        }

        if (getResponse) {
            response = GetResponse();
        }
        
        return response;
    }
    
    ~ClientLib() {
        sock.Close();
    }
}
